﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lm.Common.ExtensionMethods;

namespace Lm.Common.Auth.Account
{
    public class UserLogin
    {
        public string Login(string account, string password)
        {
            account = account.Trim();
            password = password.Trim();
            if (account.IsNullOrBlank())
            { throw new Exception("必须输入帐号"); }
            if (password.IsNullOrBlank())
            { throw new Exception("必须输入密码"); }
            password = new Lm.Common.Security.Cryptography.Md5Computer().Compute(password);
            using (var tran = new System.Transactions.TransactionScope())
            {
                var helper = Lm.Common.Auth.DAL.DALFactory.Create();
                if (helper.IsSingle<Model.Account>(t => t.UserAccount == account) == false)
                { throw new Exception("帐号不存在" + account); }
                var accountModel = helper.GetSingle<Model.Account>(t => t.UserAccount == account);

                if (accountModel.Password != password)
                { throw new Exception("密码错误"); }
                if (accountModel.Status != Model.AccountStatus.Live.ToString())
                { throw new Exception("帐号不是可用状态"); }
                if (accountModel.Pause)
                { throw new Exception("帐号为暂停状态"); }
                var token = new Model.Token()
                {
                    CreateTime = DateTime.Now,
                    ExpireTime = DateTime.Now.AddMinutes(Lm.Common.Auth.Config.ConfigReader.TokenExpireMinutes),
                    Id = Guid.NewGuid(),
                    OperatorAccount = accountModel.Id,
                    OwnerAccount = accountModel.Id,
                    UserToken = Guid.NewGuid().ToString("n")
                };
                if (helper.Insert(token) == false)
                { throw new Exception("保存Token失败"); }
                var yesterday = DateTime.Now.AddDays(-1);
                var now = DateTime.Now;
                var remark = "重新登录，新tokenId：" + token.Id;
                int i = helper.Update<Model.Token>(t => new Model.Token() { ExpireTime = yesterday, Remark = remark }, t => t.OperatorAccount == t.OwnerAccount && t.OwnerAccount == token.OwnerAccount && t.ExpireTime > now && t.Id != token.Id);
                tran.Complete();
                return token.UserToken;
            }
        }
    }
}
